﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace AES小工具
{
    public partial class FrmJson : Form
    {
        public FrmJson()
        {
            InitializeComponent();
        }

        private void btnClean_Click(object sender, EventArgs e)
        {
            if(tbJsonTxt.Text.Length == 0)
            {
                return;
            }
            tbJsonTxt.Text = string.Empty;  
        }

        private void btnFormat_Click(object sender, EventArgs e)
        {
            Format1();
        }

        private void Format1() {
            if (tbJsonTxt.Text.Length == 0)
            {
                return;
            }
            try
            {
                //JObject.ToString()方法会内部调用格式化，所以直接使用即可
                string json = tbJsonTxt.Text.Trim();
                //判读是数组还是对象
                if (json.StartsWith("["))
                {
                    JArray jobj = JArray.Parse(tbJsonTxt.Text);
                    tbJsonTxt.Text = jobj.ToString();
                }
                else if (json.StartsWith("{"))
                {
                    JObject jobj = JObject.Parse(tbJsonTxt.Text);
                    tbJsonTxt.Text = jobj.ToString();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("错误的JSON");

            }
        }

        private void Format2()
        {
            if (tbJsonTxt.Text.Length == 0)
            {
                return;
            }

            try
            {
                JsonSerializer serializer = new JsonSerializer();
                TextReader tr = new StringReader(tbJsonTxt.Text);
                JsonTextReader jtr = new JsonTextReader(tr);
                object obj = serializer.Deserialize(jtr);
                if (obj != null)
                {
                    StringWriter textWriter = new StringWriter();
                    JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                    {
                        Formatting = Formatting.Indented,
                        Indentation = 4,//缩进字符数
                        IndentChar = ' '//缩进字符
                    };
                    serializer.Serialize(jsonWriter, obj);
                    tbJsonTxt.Text = textWriter.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误的JSON");
            }
        }
    }
}
